import React, { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card } from '@/components/ui/card';
import { CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { toast } from '@/components/ui/use-toast';
import { Search, Plus, Filter, MoreHorizontal, Trash2, Edit2, Play, Eye, ChevronDown, ChevronUp, AlertCircle } from 'lucide-react';
import { Pagination, PaginationContent, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious } from '@/components/ui/pagination';

// 项目类型定义
interface Project {
  id: string;
  name: string;
  description: string;
  status: 'active' | 'inactive' | 'draft';
  modelType: 'vision' | 'text' | 'multimodal' | 'audio';
  createdAt: string;
  lastUpdated: string;
  isPublic: boolean;
}

const ProjectsPage = () => {
  const router = useRouter();
  const [projects, setProjects] = useState<Project[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [typeFilter, setTypeFilter] = useState<string>('all');
  const [sortBy, setSortBy] = useState<string>('createdAt');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
  const [currentPage, setCurrentPage] = useState(1);
  const [itemsPerPage] = useState(10);
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false);
  const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
  const [selectedProject, setSelectedProject] = useState<Project | null>(null);
  const [newProject, setNewProject] = useState({
    name: '',
    description: '',
    modelType: 'text' as 'vision' | 'text' | 'multimodal' | 'audio'
  });

  // 模拟获取项目数据
  useEffect(() => {
    const fetchProjects = async () => {
      try {
        setLoading(true);
        // 在实际应用中，这里会调用后端API获取项目列表
        // 模拟网络请求延迟
        await new Promise(resolve => setTimeout(resolve, 800));
        
        // 模拟数据
        const mockProjects: Project[] = Array.from({ length: 20 }, (_, index) => ({
          id: `project-${index + 1}`,
          name: `AI 项目 ${index + 1}`,
          description: `这是一个 ${index % 2 === 0 ? '文本' : index % 3 === 0 ? '视觉' : index % 5 === 0 ? '多模态' : '音频'} 模型项目的描述内容。`,
          status: ['active', 'inactive', 'draft'][index % 3] as 'active' | 'inactive' | 'draft',
          modelType: ['vision', 'text', 'multimodal', 'audio'][index % 4] as 'vision' | 'text' | 'multimodal' | 'audio',
          createdAt: new Date(Date.now() - index * 86400000).toISOString(),
          lastUpdated: new Date(Date.now() - index * 3600000).toISOString(),
          isPublic: index % 2 === 0
        }));
        
        setProjects(mockProjects);
      } catch (error) {
        console.error('获取项目失败:', error);
        toast({ title: '获取项目失败', description: '请稍后重试', variant: 'destructive' });
      } finally {
        setLoading(false);
      }
    };

    fetchProjects();
  }, []);

  // 处理搜索和筛选
  const filteredProjects = projects.filter(project => {
    const matchesSearch = project.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      project.description.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStatus = statusFilter === 'all' || project.status === statusFilter;
    const matchesType = typeFilter === 'all' || project.modelType === typeFilter;
    
    return matchesSearch && matchesStatus && matchesType;
  });

  // 排序处理
  const sortedProjects = [...filteredProjects].sort((a, b) => {
    if (sortBy === 'createdAt' || sortBy === 'lastUpdated') {
      const dateA = new Date(a[sortBy as keyof Project] as string).getTime();
      const dateB = new Date(b[sortBy as keyof Project] as string).getTime();
      return sortOrder === 'asc' ? dateA - dateB : dateB - dateA;
    } else {
      const valueA = (a[sortBy as keyof Project] as string).toLowerCase();
      const valueB = (b[sortBy as keyof Project] as string).toLowerCase();
      return sortOrder === 'asc' ? valueA.localeCompare(valueB) : valueB.localeCompare(valueA);
    }
  });

  // 分页处理
  const indexOfLastItem = currentPage * itemsPerPage;
  const indexOfFirstItem = indexOfLastItem - itemsPerPage;
  const currentProjects = sortedProjects.slice(indexOfFirstItem, indexOfLastItem);
  const totalPages = Math.ceil(sortedProjects.length / itemsPerPage);

  // 处理排序切换
  const handleSort = (field: string) => {
    if (sortBy === field) {
      setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
    } else {
      setSortBy(field);
      setSortOrder('desc');
    }
  };

  // 处理创建新项目
  const handleCreateProject = async () => {
    if (!newProject.name.trim()) {
      toast({ title: '创建失败', description: '项目名称不能为空', variant: 'destructive' });
      return;
    }

    try {
      // 在实际应用中，这里会调用后端API创建新项目
      await new Promise(resolve => setTimeout(resolve, 500));
      
      const createdProject: Project = {
        id: `project-${Date.now()}`,
        name: newProject.name,
        description: newProject.description,
        status: 'draft',
        modelType: newProject.modelType,
        createdAt: new Date().toISOString(),
        lastUpdated: new Date().toISOString(),
        isPublic: false
      };
      
      setProjects([createdProject, ...projects]);
      setIsCreateDialogOpen(false);
      
      // 重置表单
      setNewProject({
        name: '',
        description: '',
        modelType: 'text'
      });
      
      toast({ title: '项目创建成功', description: `已创建项目: ${createdProject.name}` });
      router.push(`/projects/${createdProject.id}`);
    } catch (error) {
      console.error('创建项目失败:', error);
      toast({ title: '创建项目失败', description: '请稍后重试', variant: 'destructive' });
    }
  };

  // 处理删除项目
  const handleDeleteProject = async () => {
    if (!selectedProject) return;

    try {
      // 在实际应用中，这里会调用后端API删除项目
      await new Promise(resolve => setTimeout(resolve, 500));
      
      setProjects(projects.filter(project => project.id !== selectedProject.id));
      setIsDeleteDialogOpen(false);
      setSelectedProject(null);
      
      toast({ title: '项目已删除', description: `已删除项目: ${selectedProject.name}` });
    } catch (error) {
      console.error('删除项目失败:', error);
      toast({ title: '删除项目失败', description: '请稍后重试', variant: 'destructive' });
    }
  };

  // 处理项目部署
  const handleDeployProject = (project: Project) => {
    toast({ title: '部署中', description: `正在部署项目: ${project.name}` });
    // 在实际应用中，这里会调用后端API部署项目
  };

  // 获取状态对应的徽章颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active':
        return 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400';
      case 'inactive':
        return 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-400';
      case 'draft':
        return 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-400';
      default:
        return 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-400';
    }
  };

  // 获取模型类型对应的标签
  const getModelTypeLabel = (type: string) => {
    switch (type) {
      case 'vision':
        return '视觉';
      case 'text':
        return '文本';
      case 'multimodal':
        return '多模态';
      case 'audio':
        return '音频';
      default:
        return type;
    }
  };

  // 格式化日期
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return new Intl.DateTimeFormat('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    }).format(date);
  };

  return (
    <div className="container mx-auto px-4 py-8">
      <div className="flex flex-col lg:flex-row lg:items-center lg:justify-between mb-6 gap-4">
        <div>
          <h1 className="text-2xl font-bold text-gray-900 dark:text-white">我的项目</h1>
          <p className="text-gray-500 dark:text-gray-400 mt-1">管理和部署您的 AI 模型项目</p>
        </div>
        
        <Button 
          className="bg-primary hover:bg-primary/90 text-white"
          onClick={() => setIsCreateDialogOpen(true)}
        >
          <Plus className="h-4 w-4 mr-2" />
          创建项目
        </Button>
      </div>

      {/* 搜索和筛选 */}
      <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-4 mb-6 border border-gray-200 dark:border-gray-700">
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-gray-400" />
            <Input
              placeholder="搜索项目名称或描述..."
              className="pl-10"
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
            />
          </div>
          
          <Select value={statusFilter} onValueChange={setStatusFilter}>
            <SelectTrigger>
              <Filter className="h-4 w-4 mr-2" />
              <SelectValue placeholder="筛选状态" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部状态</SelectItem>
              <SelectItem value="active">活跃</SelectItem>
              <SelectItem value="inactive">非活跃</SelectItem>
              <SelectItem value="draft">草稿</SelectItem>
            </SelectContent>
          </Select>
          
          <Select value={typeFilter} onValueChange={setTypeFilter}>
            <SelectTrigger>
              <Filter className="h-4 w-4 mr-2" />
              <SelectValue placeholder="筛选模型类型" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="all">全部类型</SelectItem>
              <SelectItem value="text">文本</SelectItem>
              <SelectItem value="vision">视觉</SelectItem>
              <SelectItem value="audio">音频</SelectItem>
              <SelectItem value="multimodal">多模态</SelectItem>
            </SelectContent>
          </Select>
        </div>
      </div>

      {/* 项目列表 */}
      <Card className="shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden">
        <CardHeader className="bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
          <CardTitle className="text-lg">项目列表</CardTitle>
        </CardHeader>
        <CardContent className="p-0">
          <div className="overflow-x-auto">
            <Table>
              <TableHeader className="bg-gray-50 dark:bg-gray-800">
                <TableRow>
                  <TableHead className="w-[300px] cursor-pointer" onClick={() => handleSort('name')}>
                    <div className="flex items-center">
                      项目名称
                      {sortBy === 'name' && (
                        sortOrder === 'asc' ? <ChevronUp className="h-4 w-4 ml-1" /> : <ChevronDown className="h-4 w-4 ml-1" />
                      )}
                    </div>
                  </TableHead>
                  <TableHead>描述</TableHead>
                  <TableHead className="cursor-pointer" onClick={() => handleSort('modelType')}>
                    <div className="flex items-center">
                      模型类型
                      {sortBy === 'modelType' && (
                        sortOrder === 'asc' ? <ChevronUp className="h-4 w-4 ml-1" /> : <ChevronDown className="h-4 w-4 ml-1" />
                      )}
                    </div>
                  </TableHead>
                  <TableHead className="cursor-pointer" onClick={() => handleSort('status')}>
                    <div className="flex items-center">
                      状态
                      {sortBy === 'status' && (
                        sortOrder === 'asc' ? <ChevronUp className="h-4 w-4 ml-1" /> : <ChevronDown className="h-4 w-4 ml-1" />
                      )}
                    </div>
                  </TableHead>
                  <TableHead className="cursor-pointer" onClick={() => handleSort('lastUpdated')}>
                    <div className="flex items-center">
                      最后更新
                      {sortBy === 'lastUpdated' && (
                        sortOrder === 'asc' ? <ChevronUp className="h-4 w-4 ml-1" /> : <ChevronDown className="h-4 w-4 ml-1" />
                      )}
                    </div>
                  </TableHead>
                  <TableHead className="text-right">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {loading ? (
                  // 加载状态
                  Array.from({ length: 5 }).map((_, index) => (
                    <TableRow key={`skeleton-${index}`}>
                      <TableCell colSpan={6} className="h-16">
                        <div className="flex justify-center items-center">
                          <div className="w-5 h-5 border-2 border-gray-200 border-t-primary rounded-full animate-spin" />
                          <span className="ml-2 text-gray-500">加载项目中...</span>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                ) : currentProjects.length === 0 ? (
                  // 空状态
                  <TableRow>
                    <TableCell colSpan={6} className="h-40">
                      <div className="flex flex-col items-center justify-center text-center">
                        <div className="w-12 h-12 rounded-full bg-gray-100 dark:bg-gray-800 flex items-center justify-center mb-4">
                          <AlertCircle className="h-6 w-6 text-gray-400" />
                        </div>
                        <h3 className="text-lg font-medium text-gray-900 dark:text-white mb-1">暂无项目</h3>
                        <p className="text-gray-500 dark:text-gray-400 max-w-md">
                          您还没有创建任何项目，点击"创建项目"按钮开始
                        </p>
                        <Button 
                          className="mt-4 bg-primary hover:bg-primary/90 text-white"
                          onClick={() => setIsCreateDialogOpen(true)}
                        >
                          <Plus className="h-4 w-4 mr-2" />
                          创建项目
                        </Button>
                      </div>
                    </TableCell>
                  </TableRow>
                ) : (
                  // 项目列表
                  currentProjects.map((project) => (
                    <TableRow key={project.id} className="group">
                      <TableCell className="font-medium">
                        <div className="flex items-center space-x-2">
                          {project.modelType === 'vision' && (
                            <div className="w-6 h-6 rounded-md bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center text-purple-600 dark:text-purple-400">
                              <Eye className="h-3.5 w-3.5" />
                            </div>
                          )}
                          {project.modelType === 'text' && (
                            <div className="w-6 h-6 rounded-md bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center text-blue-600 dark:text-blue-400">
                              <span className="text-xs">T</span>
                            </div>
                          )}
                          {project.modelType === 'multimodal' && (
                            <div className="w-6 h-6 rounded-md bg-green-100 dark:bg-green-900/30 flex items-center justify-center text-green-600 dark:text-green-400">
                              <span className="text-xs">MM</span>
                            </div>
                          )}
                          {project.modelType === 'audio' && (
                            <div className="w-6 h-6 rounded-md bg-orange-100 dark:bg-orange-900/30 flex items-center justify-center text-orange-600 dark:text-orange-400">
                              <span className="text-xs">🔊</span>
                            </div>
                          )}
                          <span className="hover:text-primary transition-colors cursor-pointer" onClick={() => router.push(`/projects/${project.id}`)}>
                            {project.name}
                          </span>
                          {project.isPublic && (
                            <Badge variant="secondary" className="ml-1 bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 border-0">
                              公开
                            </Badge>
                          )}
                        </div>
                      </TableCell>
                      <TableCell className="text-gray-500 dark:text-gray-400 max-w-xs truncate">
                        {project.description}
                      </TableCell>
                      <TableCell>
                        <Badge variant="outline" className="bg-gray-50 dark:bg-gray-800">
                          {getModelTypeLabel(project.modelType)}
                        </Badge>
                      </TableCell>
                      <TableCell>
                        <Badge className={getStatusColor(project.status)}>
                          {project.status === 'active' ? '活跃' : project.status === 'inactive' ? '非活跃' : '草稿'}
                        </Badge>
                      </TableCell>
                      <TableCell className="text-gray-500 dark:text-gray-400">
                        {formatDate(project.lastUpdated)}
                      </TableCell>
                      <TableCell className="text-right">
                        <div className="flex justify-end space-x-2">
                          {project.status === 'active' && (
                            <Button
                              size="sm"
                              variant="ghost"
                              className="text-primary hover:bg-primary/10"
                              onClick={() => handleDeployProject(project)}
                            >
                              <Play className="h-4 w-4 mr-1" />
                              部署
                            </Button>
                          )}
                          
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" size="icon" className="opacity-0 group-hover:opacity-100 transition-opacity">
                                <MoreHorizontal className="h-4 w-4" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuLabel>操作</DropdownMenuLabel>
                              <DropdownMenuSeparator />
                              <DropdownMenuItem onClick={() => router.push(`/projects/${project.id}`)}>
                                <Eye className="h-4 w-4 mr-2" />
                                查看
                              </DropdownMenuItem>
                              <DropdownMenuItem onClick={() => router.push(`/projects/${project.id}/edit`)}>
                                <Edit2 className="h-4 w-4 mr-2" />
                                编辑
                              </DropdownMenuItem>
                              <DropdownMenuSeparator />
                              <DropdownMenuItem 
                                className="text-red-600 dark:text-red-400"
                                onClick={() => {
                                  setSelectedProject(project);
                                  setIsDeleteDialogOpen(true);
                                }}
                              >
                                <Trash2 className="h-4 w-4 mr-2" />
                                删除
                              </DropdownMenuItem>
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {/* 分页 */}
      {!loading && sortedProjects.length > 0 && (
        <div className="mt-6 flex justify-center">
          <Pagination>
            <PaginationContent>
              <PaginationItem>
                <PaginationPrevious 
                  href="#" 
                  onClick={(e) => {
                    e.preventDefault();
                    setCurrentPage(prev => Math.max(prev - 1, 1));
                  }}
                  disabled={currentPage === 1}
                />
              </PaginationItem>
              
              {Array.from({ length: Math.min(5, totalPages) }, (_, i) => {
                let pageNum;
                if (totalPages <= 5) {
                  pageNum = i + 1;
                } else if (currentPage <= 3) {
                  pageNum = i + 1;
                } else if (currentPage >= totalPages - 2) {
                  pageNum = totalPages - 4 + i;
                } else {
                  pageNum = currentPage - 2 + i;
                }
                
                return (
                  <PaginationItem key={pageNum}>
                    <PaginationLink 
                      href="#"
                      onClick={(e) => {
                        e.preventDefault();
                        setCurrentPage(pageNum);
                      }}
                      className={currentPage === pageNum ? 'bg-primary text-white' : ''}
                    >
                      {pageNum}
                    </PaginationLink>
                  </PaginationItem>
                );
              })}
              
              <PaginationItem>
                <PaginationNext 
                  href="#" 
                  onClick={(e) => {
                    e.preventDefault();
                    setCurrentPage(prev => Math.min(prev + 1, totalPages));
                  }}
                  disabled={currentPage === totalPages}
                />
              </PaginationItem>
            </PaginationContent>
          </Pagination>
        </div>
      )}

      {/* 创建项目对话框 */}
      <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle>创建新项目</DialogTitle>
            <DialogDescription>
              填写项目信息，创建一个新的 AI 模型项目。
            </DialogDescription>
          </DialogHeader>
          
          <div className="grid gap-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="project-name">项目名称</Label>
              <Input
                id="project-name"
                placeholder="输入项目名称"
                value={newProject.name}
                onChange={(e) => setNewProject({...newProject, name: e.target.value})}
              />
            </div>
            
            <div className="space-y-2">
              <Label htmlFor="project-description">项目描述</Label>
              <Textarea
                id="project-description"
                placeholder="输入项目描述"
                className="resize-none"
                rows={3}
                value={newProject.description}
                onChange={(e) => setNewProject({...newProject, description: e.target.value})}
              />
            </div>
            
            <div className="space-y-2">
              <Label htmlFor="project-type">模型类型</Label>
              <Select 
                value={newProject.modelType}
                onValueChange={(value) => setNewProject({...newProject, modelType: value as any})}
              >
                <SelectTrigger id="project-type">
                  <SelectValue placeholder="选择模型类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="text">文本模型</SelectItem>
                  <SelectItem value="vision">视觉模型</SelectItem>
                  <SelectItem value="audio">音频模型</SelectItem>
                  <SelectItem value="multimodal">多模态模型</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          
          <DialogFooter>
            <Button variant="ghost" onClick={() => setIsCreateDialogOpen(false)}>
              取消
            </Button>
            <Button onClick={handleCreateProject} className="bg-primary hover:bg-primary/90 text-white">
              创建
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>

      {/* 删除项目对话框 */}
      <Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
        <DialogContent className="sm:max-w-md">
          <DialogHeader>
            <DialogTitle className="text-red-600 dark:text-red-400">删除项目</DialogTitle>
            <DialogDescription>
              此操作无法撤销。删除后，项目的所有数据将被永久移除。
            </DialogDescription>
          </DialogHeader>
          
          {selectedProject && (
            <div className="py-4">
              <div className="flex items-center justify-center p-4 bg-red-50 dark:bg-red-950/30 rounded-md">
                <AlertCircle className="h-8 w-8 text-red-500 dark:text-red-400" />
              </div>
              <p className="mt-4 text-center text-gray-500 dark:text-gray-400">
                确定要删除项目 "<span className="font-medium text-gray-900 dark:text-white">{selectedProject.name}</span>" 吗？
              </p>
            </div>
          )}
          
          <DialogFooter>
            <Button variant="ghost" onClick={() => setIsDeleteDialogOpen(false)}>
              取消
            </Button>
            <Button 
              className="bg-red-600 hover:bg-red-700 text-white"
              onClick={handleDeleteProject}
            >
              删除
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
};

export default ProjectsPage;